#!/bin/bash
# soon, #!/usr/local/bin/swamp_client.py --

# Purpose: Compute time anomaly from homogenized AR4 datasets
# Homogenized means that "raw" PCMDI files were:
# 1. Named with standard scn_mdl_run_YYYYMM_YYYYMM.nc convention
# 2. Have an area-weight variable named "area"

# Usage:
# python swamp_client.py ipcctest.swamp 
# export SWAMPURL='http://pbs.ess.uci.edu:8080/SOAP';python ~/swamp/src/swamp_client.py ~/swamp/demo/ipcctest.swamp

# Switch between local and swamp path roots.
if [ $SHELL = "swamp" ] ; then 
  IPCCROOT=/pcmdi
else
  exit
# Something like this would work with accounts on PCMDI's server 
# if the files were named with the YYYY convention used below
  IPCCROOT=http://user:password@climate.llnl.gov/cgi-bin/dap-cgi.py/ipcc4
fi

models=(cccma_cgcm3_1 cccma_cgcm3_1_t63 cnrm_cm3 csiro_mk3_0 \
gfdl_cm2_0 gfdl_cm2_1 giss_aom giss_model_e_h \
iap_fgoals1_0_g inmcm3_0 ipsl_cm4  miroc3_2_medres \
miub_echo_g mpi_echam5 mri_cgcm2_3_2a ncar_ccsm3_0 ncar_pcm1 \
ukmo_hadcm3 ukmo_hadgem1)

# giss_model_e_r is only available in/for run2
# miroc3_2_hires is not available
# area variable not available in some (all?) of these

variables=tas,pr 
scenarios=sresa1b 
run=run1

for scn in $scenarios; do 
    for mdl in $models; do 
	# Should add -w area weight switch when datasets have area
        ncwa -O -v $variables -a lat,lon -p $IPCCROOT/$scn \
           ${scn}_${mdl}_${run}_200001_209912.nc \
           ${scn}_${mdl}_200001_209912_xy.nc 
	# Anomalies are relative to year 2000 average 
        ncwa -F -d time,1,12 ${scn}_${mdl}_200001_209912_xy.nc ${scn}_${mdl}_2000.nc 
	# Compute anomalies for each model
        ncdiff ${scn}_${mdl}_200001_209912_xy.nc ${scn}_${mdl}_2000.nc ${scn}_${mdl}_anm.nc 
    done # end loop over model 
    # Create model ensemble
    ncea *_200001_209912_xy.nc ${scn}_avg_200001_209912_xy.nc 
    # Ensemble mean of year 2000
    ncwa -F -d time,1,12 ${scn}_avg_200001_209912_xy.nc ${scn}_avg_2000.nc 
    # Create ensemble anomaly
    ncdiff ${scn}_avg_200001_209912_xy.nc ${scn}_avg_2000.nc ${scn}_avg_anm.nc 
done # end loop over scenario

# The following are available pre-defined variables that you can
# reference in your scripts.
# SWAMPVERSION : "0.1+" -- version number, perhaps useful in the future.
# SWAMPHOSTNAME" : <hostname> -- the hostname for the swamp service,
#                  probably a fully-qualified domain name (FQDN).
# SHELL : "swamp" -- This is always set to "swamp" in the SWAMP environment

